package com.biwin.core.main.redis;

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Field;

/**
 * BiWin Framework Basic Redis Operation Util
 *
 * Use Default Serializer for Key and Value
 *
 * @author biwin
 * @since 0.0.1
 */
@EnableCaching
@Configuration
public class BwRedisConfiguration {
    private static final Log log = LogFactory.getLog(BwRedisConfiguration.class);
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public RedisTemplate<String, Object> bwRedisTemplate() {
        RedisTemplate<String, Object>  redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 往redis中存入时，序列化成json串
        redisTemplate.setValueSerializer(jsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    private GenericJackson2JsonRedisSerializer jsonRedisSerializer() {
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        try {
            Class<? extends GenericJackson2JsonRedisSerializer> jsonRedisClazz = jsonRedisSerializer.getClass();
            Field field = jsonRedisClazz.getDeclaredField("mapper");
            field.setAccessible(true);
            ObjectMapper objectMapper = (ObjectMapper) field.get(jsonRedisSerializer);
            objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        } catch (Exception e) {
            log.error("");
            e.printStackTrace();
        }
        return jsonRedisSerializer;
    }

}
